<template>
  <div class="content-box">
    <template v-if="dataList.length">
      <a-card size="small" v-for="(item, index) in dataList" :key="index"
              style="margin-bottom: 10px"
              :title="item.status == 5 ? '作废结转信息' : '新建结转信息'">
        <template #extra>
          <a-space v-if="item.status == 0">
            <a-button danger @click="handleDelete(item)">删除</a-button>
            <a-button type="primary" ghost @click="handleEdit(item)">编辑</a-button>
          </a-space>
          <a-space v-else>
            <a-button v-if="item.url" type="primary" ghost @click="viewApproval(item)">查看审批
            </a-button>
            <a-button v-if="item.status == 2" danger @click="handleVoid(item)">作废</a-button>
          </a-space>

        </template>
        <a-table
            :dataSource="item.data"
            :columns="columns"
            :pagination="false"
            rowKey="id"
            :loading="loading"
        >
          <template #bodyCell="{ text, record, index, column }">
            <template v-if="column.key == 'amount'">
              <a-tag color="green" v-if="record.isInto">入</a-tag>
              <a-tag color="red" v-else>出</a-tag>
              {{ text || 0 }}
            </template>
            <template v-if="column.key === 'created_at'">
              <template v-if="String(record.id).includes('carry')">
                <cu-icon type="org-fenzhi" style="font-size: 18px"></cu-icon>
                <span v-if="record.isInto">
                <a-tag color="green">入</a-tag>
                {{
                    `从【${record.owner_name}】的【${record.village_name}-${record.build_name}-${record.roomInfo}】 【${record.contractOn}】期【${record.cost_type_txt}】账单中抵扣了【${record.amount}】元`
                  }}
              </span>
                <span v-else>
                <a-tag color="red">出</a-tag>
                  {{
                    `抵扣了【${record.owner_name}】的【${record.village_name}-${record.build_name}-${record.roomInfo}】 【${record.contractOn}】期【${record.cost_type_txt}】账单【${record.amount}】元`
                  }}
              </span>
              </template>
              <span v-else>{{ record.updated_at }}</span>
            </template>
            <template v-if="column.key == 'enclosure'">
              <span v-if="item.object_id">
                <a-button @click="attachment(item.object_id)" type="link">附件</a-button>
              </span>
              <span v-else>--</span>
            </template>
          </template>
        </a-table>
      </a-card>
    </template>
    <template v-else>
      <div class="empty-box">
        <a-empty/>
      </div>
    </template>

    <!--  作废结转  -->
    <VoidCarryOverModal
        :visible="voidVisible"
        :id="voidId"
        @handleSuccess="handleVoidOk"
        @handleClose="handleVoidCancel"
    />

    <a-modal v-model:visible="appendix" :width="800" title="结转附件" :footer="null"
             @cancel="handleOk">
      <attachment-info
          v-if="appendix"
          :active="appendix"
          :params="attachParams"
          :showOption="false"
          :titles="false"
          :object="false"
      />
    </a-modal>
  </div>
</template>

<script>
import {defineComponent, watch, computed, reactive, toRefs} from "vue";
import {
  CaretRightOutlined,
  ExclamationCircleOutlined,
  EditOutlined,
} from "@ant-design/icons-vue";
import {useRoute, useRouter} from "vue-router";
import store from "../../../store/index";
import request from "@/common/utils/request";
import _ from "lodash";
import {TextTip} from "bl-common-vue3";
import BLCOMMON from "bl-common-vue3";
import utils from "@/common/utils/utils";
import {message} from "ant-design-vue";
import VoidCarryOverModal from "@/views/bill/BillDetail/modules/VoidCarryOverModal.vue";
import AttachmentInfo from "@/components/contract/AttachmentInfo/index.vue";

export default defineComponent({
  name: "CarryForwardList",
  props: {
    active: {
      type: Boolean,
      default: false,
    },
    showType: {
      type: String,
      default: '',
    },
    drawerId: {
      type: [Number, String],
      default: '',
    },
  },
  components: {
    AttachmentInfo,
    VoidCarryOverModal,
    CaretRightOutlined,
    ExclamationCircleOutlined,
    EditOutlined,
    TextTip
  },
  setup(props, {emit}) {
    const $route = useRoute();
    const $router = useRouter();
    const id = computed(() => props.showType === 'drawer' ? Number(props.drawerId) : Number($route.query.id));

    const state = reactive({
      columns: COLUMNS,
      dataList: [],
      iframeUrl: '',
      loading: false,
      voidVisible: false,
      voidId: 0,
      appendix: false,
      attachParams: {
        type: 1,
        object_id: '',
      },
      contractId: 0,
    });

    const getDataList = () => {
      state.loading = true;
      request.get('/org', "/billTransfer/transferList", {contract_id: id.value}).then((res) => {
        let sourceData = res?.list || [];
        sourceData.forEach((v) => {
          (v.data || []).forEach((item) => {
            item.id = item.origin_bill_id;
            item.isInto = item.type === 'into';
            if (item.children?.length) {
              item.children = item.children.map((child) => {
                return {
                  ...child,
                  id: `carry_${child.from_bill_id}`,
                  isInto: item.type === 'into',
                }
              })
            } else {
              delete item.children
            }
          })
        })
        state.dataList = sourceData;
      }).finally(() => {
        state.loading = false;
      })
    };

    const handleEdit = (item) => {
      emit("closeAllModal");
      // 编辑结转
      $router.push({
        name: "contractCarryOver",
        query: {id: id.value, task_key: item.task_key},
      });
    };


    const handleVoidCancel = () => {
      state.voidVisible = false;
    };

    const handleVoidOk = () => {
      handleVoidCancel();
      getDataList();
    };

    // 查看审批
    const viewApproval = (item) => {

      if (window.__MICRO_APP_ENVIRONMENT__) {

        window.microApp.forceDispatch({
          type: "SetChildDrawerList",
          info: {
            props: {
              title: '审批详情',
              closable: true,
              maskClosable: true,
              visible: true,
              width: 1000,
              bodyStyle: {
                height: '100%',
                boxSizing: 'border-box',
                overflowY: 'auto',
                background: '#ffffff'
              },
              destroyOnClose: true,
            },
            microId: `approvalDetailMessage`,
            app: 'workApproval',
            url: `/approval/detail?id=${item.approval_id}`,
            params: {
              isMainDrawer: true,
              closeApproval: () => {
                getDataList()
              }
            }
          }
        })
      }

    };

    // 作废
    const handleVoid = (item) => {
      state.voidId = item.task_key;
      state.voidVisible = true;
    };

    // 删除结转信息
    const handleDelete = (item) => {
      utils.modalConfirm({
        content: "确认删除此结转吗？",
        centered: true,
        okType: "danger",
        onOk: () => {
          request
              .del("/org", "/billTransfer/delTransfer", {
                task_key: item.task_key,
              })
              .then((res) => {
                message.success("删除成功");
                getDataList();
              });
        },
      });
    };

    const attachment = (id) => {

      state.attachParams.object_id = id
      state.appendix = true
      console.log(id, state.attachParams)
    }

    const handleOk = () => {
      state.attachParams.object_id = ''
      state.appendix = false
    }

    watch(
        () => props.active,
        (val) => {
          if (val) {
            getDataList();
          }
        }
    );

    return {
      ...toRefs(state),
      handleEdit,
      handleDelete,
      viewApproval,
      handleVoid,
      handleVoidCancel,
      handleVoidOk,
      attachment,
      handleOk,
    };
  },
});

const COLUMNS = [
  {
    title: "结转时间",
    dataIndex: "created_at",
    key: "created_at",
    customCell: (record, rowIndex) => {
      return {
        colSpan:
            String(record.id).includes('carry') ? 7 : 1,
      };
    },
  },
  {
    title: "区间",
    dataIndex: "contractOn",
    key: "contractOn",
    customCell: (record, rowIndex) => {
      return {
        style: {
          display: String(record.id).includes('carry')
              ? "none"
              : "",
        },
        colSpan: String(record.id).includes('carry') ? 0 : 1,
      };
    },
  },
  {
    title: BLCOMMON.utils.L("租客"),
    dataIndex: "owner_name",
    key: "owner_name",
    customCell: (record, rowIndex) => {
      return {
        style: {
          display: String(record.id).includes('carry')
              ? "none"
              : "",
        },
        colSpan: String(record.id).includes('carry') ? 0 : 1,
      };
    },
  },
  {
    title: "费用类型",
    dataIndex: "cost_type_txt",
    key: "cost_type_txt",
    customCell: (record, rowIndex) => {
      return {
        style: {
          display: String(record.id).includes('carry')
              ? "none"
              : "",
        },
        colSpan: String(record.id).includes('carry') ? 0 : 1,
      };
    },
  },
  {
    title: "项目",
    dataIndex: "village_name",
    key: "village_name",
    customCell: (record, rowIndex) => {
      return {
        style: {
          display: String(record.id).includes('carry')
              ? "none"
              : "",
        },
        colSpan: String(record.id).includes('carry') ? 0 : 1,
      };
    },
  },
  {
    title: "楼层-房号",
    dataIndex: "roomInfo",
    key: "roomInfo",
    customCell: (record, rowIndex) => {
      return {
        style: {
          display: String(record.id).includes('carry')
              ? "none"
              : "",
        },
        colSpan: String(record.id).includes('carry') ? 0 : 1,
      };
    },
  },
  {
    title: "结转金额",
    dataIndex: "amount",
    key: "amount",
    customCell: (record, rowIndex) => {
      return {
        style: {
          display: String(record.id).includes('carry')
              ? "none"
              : "",
        },
        colSpan: String(record.id).includes('carry') ? 0 : 1,
      };
    },
  },
  {
    title: "附件",
    dataIndex: "enclosure",
    key: "enclosure",
    customCell: (record, rowIndex) => {
      return {
        style: {
          display: String(record.id).includes('carry')
              ? "none"
              : "",
        },
        colSpan: String(record.id).includes('carry') ? 0 : 1,
      };
    },
  },
];

</script>

<style lang="less" scoped>
@colHeight: 40px;
.content-box {
  position: relative;
  min-height: 100%;
}

.empty-box {
  position: absolute;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

:deep(.ant-table-tbody > tr:last-child td) {
  border-bottom: none;
}

:deep(.ant-table) {
  .ant-table-tbody tr:nth-child(2n) td {
    background-color: initial !important;
  }
}

:deep(.ant-table-row-level-1) {
  background-color: #e0e0e0 !important;

  td {
    padding: 8px 16px;
  }
}
</style>
